<template>
    <div class="full-screen-layout">
        <Header />
        <div class="LoginBox">
            <div class="box">
                <div class="left"></div>
                <div class="right">
                    <h4>{{ isRegister ? '注册' : isForgotPassword ? '找回密码' : '登录' }}</h4>
                    <form action="">
                        <input v-if="!isForgotPassword" v-model="form.username" class="acc" type="text"
                            placeholder="用户名">
                        <input v-if="!isForgotPassword" v-model="form.password" class="acc" type="password"
                            placeholder="密码">
                        <input v-if="isRegister" v-model="form.confirmPassword" class="acc" type="password"
                            placeholder="确认密码">

                        <!-- 找回密码表单 -->
                        <div v-if="isForgotPassword" class="forgot-password-form">
                            <input v-model="forgotForm.email" class="acc" type="email" placeholder="注册邮箱">
                            <div class="verify-code" v-if="!codeSent">
                                <button class="send-code-btn" @click.prevent="sendVerifyCode">发送验证码</button>
                            </div>
                            <div class="verify-code" v-else>
                                <input v-model="forgotForm.verifyCode" class="acc" type="text" placeholder="验证码">
                                <button class="send-code-btn" @click.prevent="resetPassword">重置密码</button>
                            </div>
                        </div>

                        <input v-if="!isForgotPassword" class="submit" type="submit" :value="isRegister ? '注册' : '登录'"
                            @click.prevent="isRegister ? userRegister() : userLogin()">
                    </form>
                    <div class="fn">
                        <a href="javascript:;" @click="toggleForm">{{ getToggleText }}</a>
                        <a v-if="!isRegister && !isForgotPassword" href="javascript:;"
                            @click="toggleForgotPassword">找回密码</a>
                        <a v-if="isForgotPassword" href="javascript:;" @click="toggleForgotPassword">返回登录</a>
                    </div>
                </div>
            </div>
        </div>
        <Footer />
    </div>
</template>
<script setup>
import { ref, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import Header from '@/components/Header.vue';
import Footer from '@/components/Footer.vue';
import { useUserStore } from '@/stores/user';


const router = useRouter();
const userStore = useUserStore();
const isRegister = ref(false);
const isForgotPassword = ref(false);
const codeSent = ref(false);
const form = reactive({
    username: 'user001',
    password: '123456',
    confirmPassword: ''
});
const forgotForm = reactive({
    email: '',
    verifyCode: ''
});
const getToggleText = computed(() => {
    if (isForgotPassword.value) return '';
    return isRegister.value ? '已有账号？登录' : '注册账号';
});

const toggleForm = () => {
    isRegister.value = !isRegister.value;
    isForgotPassword.value = false;
    form.confirmPassword = '';
};
const toggleForgotPassword = () => {
    isForgotPassword.value = !isForgotPassword.value;
    isRegister.value = false;
};
const validateEmail = (email) => {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(email);
};
const sendVerifyCode = async () => {
    if (!forgotForm.email) {
        ElMessage.warning('请输入邮箱地址');
        return;
    }

    if (!validateEmail(forgotForm.email)) {
        ElMessage.warning('请输入有效的邮箱地址');
        return;
    }

    try {
        await sendResetCode(forgotForm.email);
        ElMessage.success('验证码已发送到您的邮箱');
        codeSent.value = true;
    } catch (error) {
        ElMessage.error('发送验证码失败: ' + (error.response?.data?.message || error.message));
    }
};

const resetPassword = async () => {
    if (!forgotForm.verifyCode) {
        ElMessage.warning('请输入验证码');
        return;
    }

    try {
        const response = await verifyResetCode({
            email: forgotForm.email,
            code: forgotForm.verifyCode
        });

        ElMessage.success(`新密码已发送到您的邮箱: ${forgotForm.email}`);
        toggleForgotPassword();
    } catch (error) {
        ElMessage.error('重置密码失败: ' + (error.response?.data?.message || error.message));
    }
};

const validateForm = () => {
    if (!form.username || !form.password) {
        ElMessage.warning('用户名和密码不能为空');
        return false;
    }
    if (isRegister.value && form.password !== form.confirmPassword) {
        ElMessage.warning('两次输入的密码不一致');
        return false;
    }
    return true;
};

const userLogin = async () => {
    if (!validateForm()) return;

    try {
        console.log('username:', form.username)
        console.log('password:', form.password)
        const success = await userStore.login({
            username: form.username,
            password: form.password
        });

        if (success) {
            ElMessage.success('登录成功');
            const role = userStore.getUser?.role;
            console.log('role:', role);
            if (role === '家长') {
                router.push({ name: 'ParentManagementPage' });
            }
            if (role === '学生') {
                router.push({ name: 'StudentLearning' });
            }

        }
    } catch (error) {
        ElMessage.error('登录失败，' + (error.response?.data?.message || error.message));
    }
};

const userRegister = async () => {
    if (!validateForm()) return;
    try {
        const success = await userStore.register({
            username: form.username,
            password: form.password
        });

        if (success) {
            ElMessage.success('注册成功');
            toggleForm(); // 自动切换到登录界面
        }
    } catch (error) {
        ElMessage.error('注册失败，' + (error.response?.data?.message || error.message));
    }
};
</script>
<style scoped>
@import url("@/assets/css/login.css");

.forgot-password-form {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.verify-code {
    display: flex;
    gap: 10px;
}

.send-code-btn {
    padding: 0 15px;
    background: #409eff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    white-space: nowrap;
}

.send-code-btn:hover {
    background: #66b1ff;
}
</style>